<template>
  <div class="signature-wrap">
    {{ title }}
    <div
      :class="{ 'has-signature': hasSignature }"
      :style="{ width: width + 'px', height: height + 'px' }"
      class="signature-area"
    >
      <!-- 背景层 canvas 用于绘制田字格 -->
      <canvas
        ref="gridCanvasRef"
        :height="height"
        :style="{ width: width + 'px', height: height + 'px' }"
        :width="width"
        class="grid-canvas"
      ></canvas>
      <!-- 签名层 canvas -->
      <canvas
        ref="canvasRef"
        :height="height"
        :style="{ width: width + 'px', height: height + 'px' }"
        :width="width"
        class="signature-canvas"
      ></canvas>
    </div>
    <div class="signature-btns">
      <el-button @click="closeDialog">取消</el-button>
      <el-button @click="handleClear">重写</el-button>
      <el-button type="primary" @click="handleSave">确定</el-button>
      <el-button @click="handleRemoteSign">远程签字</el-button>
    </div>
  </div>

  <!-- 远程签字二维码对话框 -->
  <Dialog v-model="qrCodeDialogVisible" append-to-body title="远程签字" width="400px">
    <div style="text-align: center; padding: 20px 0">
      <Qrcode :text="qrCodeUrl" :width="300" />
      <div style="margin-top: 20px; color: #666; font-size: 14px">
        链接已自动复制到剪贴板，有效时间1个小时
      </div>
    </div>
  </Dialog>
</template>

<script lang="ts" setup>
import { defineEmits, defineExpose, defineProps, nextTick, onMounted, ref, watch } from 'vue'
import SignaturePad from 'signature_pad'
import { ElMessage } from 'element-plus'
import * as UserApi from '@/api/system/user'
import { Qrcode } from '@/components/Qrcode'
import Dialog from '@/components/Dialog/src/Dialog.vue'
import { useClipboard } from '@vueuse/core'

const props = defineProps({
  modelValue: String, // base64
  nickname: String, // base64
  id: String, // base64
  title: String, // base64
  projectId: String, // base64
  reportType: String, // base64
  signRole: String, // base64
  width: { type: Number, default: 850 },
  height: { type: Number, default: 450 },
  type: { type: Number, default: 1 },
})
const emit = defineEmits(['update:modelValue', 'save', 'closeDialog'])
const canvasRef = ref<HTMLCanvasElement | null>(null)
const gridCanvasRef = ref<HTMLCanvasElement | null>(null)
const hasSignature = ref(false)
let signaturePad: SignaturePad | null = null
const qrCodeDialogVisible = ref(false)
const qrCodeUrl = ref('')
const { copy } = useClipboard()

const closeDialog = () => {
  emit('closeDialog')
}

// 提取 nickname 中的中文字符数组
const getChineseChars = (text: string): string[] => {
  if (!text) return []
  // 匹配中文字符
  const chineseRegex = /[\u4e00-\u9fa5]/g
  const matches = text.match(chineseRegex)
  return matches || []
}

// 绘制虚线田字格
const drawGrid = () => {
  if (!gridCanvasRef.value) return

  const canvas = gridCanvasRef.value
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 获取中文字符数组
  const chineseChars = getChineseChars(props.nickname || '')
  const chineseCount = chineseChars.length
  if (chineseCount === 0) return

  // 计算每个田字格的大小 - 减小边距和间距，让田字格更大
  const padding = 10 // 左右边距（从20减小到10）
  const topPadding = 10 // 上边距（从20减小到10）
  const bottomPadding = 10 // 下边距（从20减小到10）
  const gridSpacing = 5 // 田字格之间的间距（从10减小到5）
  const availableWidth = props.width - padding * 2
  const availableHeight = props.height - topPadding - bottomPadding

  // 计算每个田字格的宽度和高度 - 让田字格尽可能大，充分利用空间
  const gridWidth = (availableWidth - gridSpacing * (chineseCount - 1)) / chineseCount
  // 让田字格高度尽可能大，充分利用可用高度，但不超过宽度（保持正方形）
  const gridHeight = Math.min(gridWidth, availableHeight * 0.95) // 使用95%的可用高度，增加使用率

  // 计算垂直居中位置 - 减少顶部空白
  const startY = topPadding + (availableHeight - gridHeight) / 2

  // 定义不同颜色用于区分田字格
  const gridColors = [
    '#409eff',
    '#67c23a',
    '#e6a23c',
    '#f56c6c',
    '#909399',
    '#9c27b0',
    '#00bcd4',
    '#ff9800'
  ]

  // 绘制每个田字格
  for (let i = 0; i < chineseCount; i++) {
    const startX = padding + i * (gridWidth + gridSpacing)
    const char = chineseChars[i]
    const gridColor = gridColors[i % gridColors.length] // 循环使用颜色

    // 设置虚线样式，使用不同的颜色区分每个田字格
    ctx.strokeStyle = gridColor
    ctx.lineWidth = 1.5
    ctx.setLineDash([5, 5]) // 虚线：5px 实线，5px 空白

    // 绘制外框
    ctx.strokeRect(startX, startY, gridWidth, gridHeight)

    // 绘制中间十字线
    // 竖线
    ctx.beginPath()
    ctx.moveTo(startX + gridWidth / 2, startY)
    ctx.lineTo(startX + gridWidth / 2, startY + gridHeight)
    ctx.stroke()

    // 横线
    ctx.beginPath()
    ctx.moveTo(startX, startY + gridHeight / 2)
    ctx.lineTo(startX + gridWidth, startY + gridHeight / 2)
    ctx.stroke()

    // 恢复实线
    ctx.setLineDash([])

    // 在田字格中心绘制字符（楷体，半透明）
    ctx.save()
    // 字体大小根据田字格大小调整，确保字符合适显示
    const fontSize = Math.min(gridWidth, gridHeight)
    ctx.font = `${fontSize}px "楷体", "KaiTi", "STKaiti", "STKaiTi", "SimKai", serif`
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillStyle = gridColor
    ctx.globalAlpha = 0.15 // 设置透明度为25%，让字符更虚一些
    ctx.fillText(char, startX + gridWidth / 2, startY + gridHeight / 2)
    ctx.restore()
  }
}

onMounted(() => {
  nextTick(() => {
    // 绘制田字格
    drawGrid()

    if (canvasRef.value) {
      signaturePad = new SignaturePad(canvasRef.value, {
        minWidth: 4,
        maxWidth: 7,
        penColor: '#2c3e50',
        backgroundColor: 'rgba(255,255,255,0)'
      })

      // 监听签名开始和结束事件
      signaturePad.addEventListener('beginStroke', () => {
        hasSignature.value = true
      })

      // 回显
      if (props.modelValue) {
        signaturePad.fromDataURL(props.modelValue)
        hasSignature.value = !signaturePad.isEmpty()
      }
    }
  })
})

watch(
  () => props.modelValue,
  (val) => {
    if (signaturePad) {
      signaturePad.clear()
      if (val) {
        signaturePad.fromDataURL(val)
        hasSignature.value = !signaturePad.isEmpty()
      } else {
        hasSignature.value = false
      }
    }
  },
  { immediate: true }
)

// 监听 nickname、width、height 变化，重新绘制田字格
watch(
  () => [props.nickname, props.width, props.height],
  () => {
    nextTick(() => {
      drawGrid()
    })
  },
  { immediate: false }
)

const getSignTask = async () => {
  const data = await UserApi.addSignTask({
    id: props.id,
    projectId: props.projectId,
    reportType: props.reportType,
    signRole: props.signRole,
    nickname: props.nickname,
    type: props.type //1 从用户管理签名页来的 2从签字页面来的
  })
  return data
}

// 处理远程签字
const handleRemoteSign = async () => {
  try {
    const uuid = await getSignTask()

    if (!uuid) {
      ElMessage.error('获取签字任务失败，请重试')
      return
    }

    // 拼接地址
    // const url = `http://192.168.1.4:80/#/sign?taskId=${uuid}`
    const url = import.meta.env.VITE_BASE_URL+'/#/sign?taskId='+uuid
    qrCodeUrl.value = url

    // 复制到剪贴板
    await copy(url)
    ElMessage.success('链接已复制到剪贴板')

    // 显示二维码对话框
    qrCodeDialogVisible.value = true
  } catch (error) {
    console.error('远程签字失败:', error)
    ElMessage.error('远程签字失败，请重试')
  }
}

function handleClear() {
  if (signaturePad) {
    signaturePad.clear()
    hasSignature.value = false
  }
}

function handleSave() {
  if (!signaturePad) return
  if (signaturePad.isEmpty()) {
    ElMessage.error('请先签名')
    return
  }
  const data = signaturePad.toDataURL()
  emit('update:modelValue', data)
  emit('save', data)
}

// 允许父组件调用清空
defineExpose({
  clear: handleClear
})
</script>

<style scoped>
.signature-wrap {
}

.signature-area {
  border: 1.5px solid #e4e7ed;
  border-radius: 12px;
  background: #f7f8fa;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.2s;
  position: relative;
}

.signature-area:hover {
  border-color: #409eff;
}

.grid-canvas {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
  pointer-events: none;
}

.signature-canvas {
  position: relative;
  z-index: 1;
}

.signature-btns {
  margin-top: 18px;
  display: flex;
  justify-content: center;
  gap: 18px;
}

/* 添加签名区域的提示文字样式 */
.signature-area::after {
  content: '请在此区域内签名';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #c0c4cc;
  font-size: 14px;
  pointer-events: none;
  opacity: 0.6;
  z-index: 1;
}

.signature-area.has-signature::after {
  display: none;
}
</style>
